package com.jinlejia.erp.ui.house.prospect;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;

import com.donkingliang.imageselector.utils.ImageSelector;
import com.jinlejia.erp.R;
import com.jinlejia.erp.adapter.prospect.UploadHouseTypeImageAdapter;
import com.jinlejia.erp.adapter.prospect.UploadImageGridViewAdapter;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.databinding.FragmentProspectUploadHouseTypeBinding;
import com.jinlejia.erp.ui.house.prospect.bean.SurveyPictureBean;

import java.io.File;
import java.net.URLEncoder;
import java.util.ArrayList;

import top.zibin.luban.LubanZ;

/**
 * A simple {@link Fragment} subclass.
 */
public class ProspectUploadHouseTypeFragment extends Fragment implements ProspectUploadImageActivity.HouseTypePictureListener{


    public ProspectUploadHouseTypeFragment() {
        // Required empty public constructor
    }

    private Helper helper;

    public static ProspectUploadHouseTypeFragment newInstance(int pageType, String houseType, String houseSourceCode, String houseSourceType, SurveyPictureBean bean) {
        ProspectUploadHouseTypeFragment fragment = new ProspectUploadHouseTypeFragment();
        Bundle args = new Bundle();
        args.putString(Type.PARAM.HOUSE_TYPE, houseType);
        args.putString(Type.PARAM.HOUSE_SOURCE_CODE,houseSourceCode);
        args.putString(Type.PARAM.HOUSE_SOURCE_TYPE,houseSourceType);
        args.putInt(Type.PARAM.PAGE_TYPE,pageType);
        args.putParcelable(Type.PARAM.HOUSE_SOURCE_INFO,bean);
        fragment.setArguments(args);
        return fragment;
    }

    private static final int REQUEST_SELECT_FLOOR_PLAN = 20;

    private UploadImageGridViewAdapter mAdapter;

    private FragmentProspectUploadHouseTypeBinding binding;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_prospect_upload_house_type, container, false);
        binding = DataBindingUtil.bind(view);
        helper = Helper.init(getContext());
        initView();
        Bundle bundle = getArguments();
        SurveyPictureBean bean = bundle.getParcelable(Type.PARAM.HOUSE_SOURCE_INFO);
        String houseSourceCode = bundle.getString(Type.PARAM.HOUSE_SOURCE_CODE);
        String houseSourceType = bundle.getString(Type.PARAM.HOUSE_SOURCE_TYPE);
        @SuppressWarnings("unused") FragmentHelper fragmentHelper = FragmentHelper.init(this, houseSourceCode, houseSourceType, helper);
        initView(bean);
        return view;
    }


    private ArrayList<String> cachePictures = new ArrayList<>();

    private void initView(SurveyPictureBean bean){
        if (bean==null)return;
        UploadImageGridViewAdapter.Source s = new UploadImageGridViewAdapter.Source();
        String apartment = bean.getApartment();
        s.setPictureUrl(ApiConfig.MAGEHEADER_URL() + apartment);
        s.setServerUrl(apartment);
        if (!TextUtils.isEmpty(apartment)){
            mAdapter.addSource(s);
        }
    }

    private void initView() {
        if (mAdapter!=null)return;
        //户型图 只上传一张
        mAdapter = new UploadImageGridViewAdapter(binding.floorPlanHeaderView.getLabel(),getContext(), 1,false, new UploadImageGridViewAdapter.UploadListener() {
            @Override
            public void onSelectPicture(int lastShowCount) {
                ImageSelector.builder()
                        .useCamera(true)
                        .setMaxSelectCount(1)
                        .setSelected(cachePictures)
                        .setViewImage(true)
                        .start(ProspectUploadHouseTypeFragment.this, REQUEST_SELECT_FLOOR_PLAN);
            }

            @Override
            public void onSelectSubdivided(ArrayList<UploadImageGridViewAdapter.Source> sources, UploadImageGridViewAdapter.Source source) {
                //empty
                //户型图 不需要选择分间信息
            }

            @Override
            public void onPreviewViePicture(ArrayList<UploadImageGridViewAdapter.Source> sources, int position, UploadImageGridViewAdapter.Source source) {
                Intent intent = new Intent();
                intent.setClass(getContext(),ProspectViewPictureActivity.class);
                intent.putExtra(ProspectViewPictureActivity.PARAM_SOURCES,sources);
                intent.putExtra(ProspectViewPictureActivity.PARAM_POSITION,position);
                startActivity(intent);
            }

            @Override
            public void onReloadPicture(UploadImageGridViewAdapter.Source source) {

            }
        });
        binding.floorPlanGridView.setAdapter(mAdapter);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_SELECT_FLOOR_PLAN) {
            ArrayList<String> list = data.getStringArrayListExtra(ImageSelector.SELECT_RESULT);
            final ArrayList<LubanZ.LubanZImage> files = new ArrayList<>();
            for (String url : list) {
                UploadImageGridViewAdapter.Source source = new UploadImageGridViewAdapter.Source();
                source.setUploadState(1); //上传图片的第一步，将上传图片的状态设置为 上传中
                source.setPictureUrl(url);
                mAdapter.addSource(source);
                LubanZ.LubanZImage image = new LubanZ.LubanZImage();
                File file = new File(url);
                if (file.exists()){
                    image.setOriginalFile(file);
                    files.add(image);
                }
            }
            innerUploadImage(files,mAdapter);
            mAdapter.notifyDataSetInvalidated();
        }
        if (resultCode == Activity.RESULT_OK && requestCode == 10){ //从服务器选择的图片
            UploadHouseTypeImageAdapter.HouseTypeSource data1 = data.getParcelableExtra("data");
            UploadImageGridViewAdapter.Source source = new UploadImageGridViewAdapter.Source();
            String imageUrl = data1.getTempImageUrl();
            source.setUploadState(0); //标识上传成功,因为图片时从服务器获取的
            source.setPictureUrl(data1.getImageUrl());
            source.setServerUrl(imageUrl);
            mAdapter.addSource(source);
            mAdapter.notifyDataSetInvalidated();
        }
    }

    private void innerUploadImage(final ArrayList<LubanZ.LubanZImage> files, final UploadImageGridViewAdapter adapter){
        ArrayList<UploadImageGridViewAdapter.Source> sources = adapter.getSources();
        helper.http().uploadImage(sources,files, new Helper.Http.UploadImageCallBack() {
            private void toUpdateSource(String fileName, String serverUrl,ArrayList<String> failedList){
                ArrayList<UploadImageGridViewAdapter.Source> sources = adapter.getSources();
                for (int i = 0; i < sources.size(); i++) {
                    UploadImageGridViewAdapter.Source source = sources.get(i);
                    String pictureUrl = source.getPictureUrl();
                    if (failedList==null || failedList.isEmpty()){
                        if (TextUtils.isEmpty(pictureUrl)){
                        }
                        if(!TextUtils.isEmpty(serverUrl)
                                && !TextUtils.isEmpty(pictureUrl)
                                && URLEncoder.encode(pictureUrl).equals(fileName)){
                            source.setServerUrl(serverUrl);
                            source.setUploadState(0); //标识上传成功
                            break;
                        }
                    }else {
                        for (String u : failedList) {
                            String url = URLEncoder.encode(source.getPictureUrl());
                            if (url.equals(u)){
                                source.setUploadState(2);
                                break;
                            }
                        }
                    }

                }
            }
            @Override
            public void onUploadSuccess(String fileName,String serverUrl) {
                toUpdateSource(fileName,serverUrl,null);
            }

            @Override
            public void onUploadComplete(ArrayList<String> failedList) {
                if (failedList!=null && !failedList.isEmpty()){
                    toUpdateSource(null,null,failedList);
                }
                adapter.notifyDataSetInvalidated();
            }
        });
    }


    @Override
    public String hahHouseTypePicture() {
        String message = null;
        ArrayList<UploadImageGridViewAdapter.Source> sources = mAdapter.getSources();
        for (UploadImageGridViewAdapter.Source source:sources) {
            if (source.getUploadState()==1){
                message ="户型图片正在上传中,请稍后...";
                break;
            }
        }
        if (sources.isEmpty()){
            message = "请上传户型图";
        }
        return message;
    }

    @Override
    public SurveyPictureBean getHouseTypeResult() {
        ArrayList<UploadImageGridViewAdapter.Source> list = mAdapter.getSources();
        String message = hahHouseTypePicture();
        if (!TextUtils.isEmpty(message)){
            return null;
        }
        UploadImageGridViewAdapter.Source source = list.get(0);
        SurveyPictureBean bean = new SurveyPictureBean();
        bean.setApartment(source.getServerUrl());
        return bean;
    }
}
